package com.flyox.game.fivetiger.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import com.flyox.game.fivetiger.tools.SubnetAddress;

public class IPClient {
	private boolean living=true;
	
	int port=5000; // 声明组播使用的端口
	InetAddress group; // 声明建立组播组使用的组播组地址
	MulticastSocket socket; // 声明建立组播组使用的MulticastSocket类
	DatagramPacket packet; // 声明发送和接收数据所使用的DatagramPacket类

	public IPClient(){
		SubnetAddress sa = new SubnetAddress();
		String s = sa.calculate();
		try {
			group = InetAddress.getByName(s);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	public String getIP(){
		send();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "";
	}
	public void send(){
		byte[] data="GET_SERVER".getBytes();
		packet = new DatagramPacket(data, data.length, group, port); // 创建一个DatagramPacket实例
		try {
			socket.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void receive() { // 用户点击“接收时间”按钮时产生的动作
		try {
			socket = new MulticastSocket(port); // 初始化MulticastSocket类并将端口号与之关联
			socket.joinGroup(group); // 加入组播组
			while(isLiving()){
				byte[] data = new byte[50];
				packet = new DatagramPacket(data, data.length, group, port); // 创建一个DatagramPacket实例
				socket.receive(packet); // 接收组播组中时间服务器传来的时间
				String message = new String(packet.getData(), 0, packet.getLength());
				System.out.println("receive:"+message);
			}
		} catch (Exception e1) {
			System.out.println("Error: " + e1); // 捕捉异常情况
		}
	}
	

	public boolean isLiving() {
		return living;
	}

	public void setLiving(boolean living) {
		this.living = living;
	}
}
